<?php

class ProductsController extends AppController {

    var $name = 'Products';
    var $pageTitle = 'Product Description';
    var $viewPath = 'its/inventories/products';
    var $uses = array('Product', 'CustProductSite', 'PictureBarcode', 'PictureProduct', 'Period', 'Customer', 'ItsStockIn', 'Supplier', 'Category', 'Brand', 'Customer', 'Site', 'ProductPriceHistory');

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_inventories');
    }

    function display() {
        parent::display('Product');
        $op = array(
            'part_no' => 'LIKE',
            'supplier_id' => '=',
            'category_id' => '=',
            'type_id' => '=',
            'brand_id' => '=',
            'model' => 'LIKE',
            'title' => 'LIKE',
            'text' => 'LIKE',
            'current_stock' => !empty($this->data['current_stock_operand']) ? $this->data['current_stock_operand'] : '>',
        );

        if (!empty($this->data['CustProductSite']['customer_id'])) {
            $product_ids = $this->CustProductSite->listProductIdByCustomerId($this->data['CustProductSite']['customer_id']);
            $this->data['Product']['id'] = $product_ids;
            $this->Session->write("CustProductSite.paging.customer_id", $this->data['CustProductSite']['customer_id']);
            $this->Customer->id = $this->data['CustProductSite']['customer_id'];
            $this->Session->write('Criteria.customer', $this->Customer->field('name'));
        }
        if (!empty($this->data['CustProductSite']['site_id'])) {
            $product_ids = $this->CustProductSite->listProductIdBySiteId($this->data['CustProductSite']['site_id']);
            $this->data['Product']['id'] = $product_ids;
            $this->Session->write("CustProductSite.paging.site_id", $this->data['CustProductSite']['site_id']);
            $this->Site->id = $this->data['CustProductSite']['site_id'];
            $this->Session->write('Criteria.site', $this->Site->field('name'));
        }
        unset($this->data['CustProductSite']);

        if (!empty($this->data)) {
            // หน้า search ปกติมี search ตามจำนวนและวันที่ด้วย
            // แต่หน้า search ที่มาจาก popup_view จะไม่มี Operand และวันที่
            if (!empty($this->data['Operand'])) {
                if ($this->data['Product']['current_stock'] != null) {
                    $this->Session->write('Criteria.current_stock', $this->data['Product']['current_stock']);
                    $this->Session->write('Operand.current_stock', $this->data['current_stock_operand']);
                }

                if (!empty($this->data['Product']['last_stock_in_date_start'])) {
                    $this->Session->write('Criteria.last_stock_in_date_start', $this->data['Product']['last_stock_in_date_start']);
                    $this->Session->write('Criteria.last_stock_in_date_end', $this->data['Product']['last_stock_in_date_end']);
                }

                if (!empty($this->data['Product']['last_dispatch_date_start'])) {
                    $this->Session->write('Criteria.last_stock_out_date_start', $this->data['Product']['last_dispatch_date_start']);
                    $this->Session->write('Criteria.last_stock_out_date_end', $this->data['Product']['last_dispatch_date_end']);
                }

                if (!empty($this->data['Product']['price_start'])) {
                    $this->Session->write('Criteria.latest_price_start', $this->data['Product']['price_start']);
                    $this->Session->write('Criteria.latest_price_end', $this->data['Product']['price_end']);
                }

                if (!empty($this->data['Product']['cost_start'])) {
                    $this->Session->write('Criteria.latest_cost_start', $this->data['Product']['cost_start']);
                    $this->Session->write('Criteria.latest_cost_end', $this->data['Product']['cost_end']);
                }
            }

            if (!empty($this->data['Product']['supplier_id'])) {
                $this->Supplier->id = $this->data['Product']['supplier_id'];
                $this->Session->write('Criteria.supplier_name', $this->Supplier->field('name'));
            }

            if (!empty($this->data['Product']['type_id'])) {
                $this->Supplier->id = $this->data['Product']['type_id'];
                $this->Session->write('Criteria.its_type', $this->ItsType->field('name'));
            }

            if (!empty($this->data['Product']['brand_id'])) {
                $this->Brand->id = $this->data['Product']['brand_id'];
                $this->Session->write('Criteria.brand_name', $this->Brand->field('name'));
            }

            if (!empty($this->data['Product']['part_no'])) {
                $this->Session->write('Criteria.part_no', $this->data['Product']['part_no']);
            }

            if (!empty($this->data['Product']['supplier_part_no'])) {
                $this->Session->write('Criteria.supplier_part_no', $this->data['Product']['supplier_part_no']);
            }

            if (!empty($this->data['Product']['title'])) {
                $this->Session->write('Criteria.title', $this->data['Product']['title']);
            }

            if (!empty($this->data['Product']['text'])) {
                $this->Session->write('Criteria.text', $this->data['Product']['text']);
            }

            if (!empty($this->data['Product']['model'])) {
                $this->Session->write('Criteria.model', $this->data['Product']['model']);
            }

            if (!empty($this->data['Product']['category_id'])) {
                $this->Category->id = $this->data['Product']['category_id'];
                $this->Session->write('Criteria.category_name', $this->Category->field('name'));
            }
        }

        unset($this->data['current_stock_operand']);
        $this->_checkBetweenSearch('Product', 'price');
        $this->_checkBetweenSearch('Product', 'cost');
        $this->_checkBetweenSearch('Product', 'last_stock_in_date');
        $this->_checkBetweenSearch('Product', 'last_dispatch_date');
        $this->_paging(Inflector::classify($this->name), $op);
    }

    function save() {
        $product_id = null;
        if (!empty($this->data)) {
            $this->Product->query("BEGIN");
            $is_success = true;
            $this->_wrap_part_no();
        }

        $this->data['Product']['collector_id'] = $this->Session->read('Auth.User.id');
        if ($this->Product->save($this->data['Product'])) {
            $is_success &= ( ($this->_barcode_upload() && $this->_picture_upload(1)) && $this->_picture_upload(2));
        } else {
            $is_success = false;
        }

        if ($is_success == true) {
            $this->Product->query("COMMIT");
            ;
            $this->Session->setFlash("Product save succesfull.", 'flash/ok');
            $product_id = $this->Product->id;
        } else {
            $this->Product->query("ROLLBACK");
            $this->Session->setFlash("Product save fail.", 'flash/fail');

            // ถ้า add ไม่ถูกให้ใส่ part no ใหม่เลย
            $this->data['Product']['supplier_id'] = null;
            $this->data['Product']['category_id'] = null;
            $this->data['Product']['type_id'] = null;
            $this->data['Product']['name'] = null;
            // ถ้าเป็น mode edit เก็บ id เอาไว้กรณีบันทึกข้อมูลผิด
            $product_id = $this->data['Product']['id'];
        }
        $this->setAction('view', $product_id);
    }

    function _wrap_part_no() {
        // ถ้าเป็น การ insert part no ธรรมดา เติมขีดลง part no
        $this->Product->Supplier->id = $this->data['Product']['supplier_id'];
        if ($this->Product->Supplier->field('special_part_no') == false) {
            $supplier_code = $this->Product->Supplier->field('code');

            $this->Product->Category->id = $this->data['Product']['category_id'];
            $category_code = $this->Product->Category->field('code');

            $this->Product->ItsType->id = $this->data['Product']['type_id'];
            $type_code = $this->Product->ItsType->field('code');

            $this->data['Product']['part_no'] = strtoupper(
                            trim((string) $supplier_code) . '-' .
                            trim((string) $category_code) . '-' .
                            trim((string) $type_code) . '-' .
                            trim((string) $this->data['Product']['name']));
        } else {
            $this->data['Product']['part_no'] = strtoupper(
                            trim((string) $this->data['Product']['special_supplier']) . '-' .
                            trim((string) $this->data['Product']['special_part_no']));
            $this->data['Product']['category_id'] = $this->data['Product']['special_category_id'];
        }
    }

    function _barcode_upload() {
        if (is_uploaded_file($this->data['Picture']['barcode']['tmp_name'])) {
            if ($this->data['Picture']['barcode']['size'] > Product::PICTURE_SIZE_LIMIT) {
                $this->Product->validationErrors['barcode'] = 'Barcode image has reached size limit.';
                return false;
            } else {
                $fileData = fread(fopen($this->data['Picture']['barcode']['tmp_name'], "r"),
                                $this->data['Picture']['barcode']['size']);

                // ถ้าเป็นการ update ให้ลบ แล้ว insert ใหม่
                if ($this->data['mode'] == 'edit' && $this->Product->field("has_barcode") == true) {
                    $this->PictureBarcode->delete($this->Product->id);
                }

                $part_no = $this->Product->field('part_no');
                $this->data['PictureBarcode']['product_id'] = $this->Product->id;
                $this->data['PictureBarcode']['name'] = $part_no . '_bc';
                $this->data['PictureBarcode']['type'] = $this->data['Picture']['barcode']['type'];
                $this->data['PictureBarcode']['size'] = $this->data['Picture']['barcode']['size'];
                $this->data['PictureBarcode']['image'] = $fileData;
                if ($this->PictureBarcode->save($this->data)) {
                    $this->Product->saveField('has_barcode', true);
                    return true;
                }
            }
        }
        // ไม่ได้ upload barcode ขึ้นมา
        return true;
    }

    /**
     *
     * @param int $i ในฐานข้อมูล field num เริ่มที่ 1, 2 ใน index ใช้ 0, 1
     */
    function _picture_upload($i) {
        if (is_uploaded_file($this->data['Picture']["product_{$i}"]['tmp_name'])) {
            if ($this->data['Picture']['barcode']['size'] > Product::PICTURE_SIZE_LIMIT) {
                $this->Product->validationErrors["product_{$i}"] = 'Barcode image has reached size limit.';
                return false;
            } else {
                $fileData = fread(fopen($this->data['Picture']["product_{$i}"]['tmp_name'], "r"),
                                $this->data['Picture']["product_{$i}"]['size']);

                // ถ้าเป็นการ update ให้ลบ แล้ว insert ใหม่
                if ($this->data['mode'] == 'edit' && $this->Product->field("has_picture_{$i}") == true) {
                    // deleteAll ใส่ Condition ได้
                    $this->PictureProduct->deleteAll(array('product_id' => $this->Product->id, 'num' => $i));
                }

                $this->PictureProduct->create();
                $part_no = $this->Product->field('part_no');
                $this->data['PictureProduct']['num'] = $i;
                $this->data['PictureProduct']['product_id'] = $this->Product->id;
                $this->data['PictureProduct']['name'] = $part_no . '_' . $i;
                $this->data['PictureProduct']['type'] = $this->data['Picture']["product_{$i}"]['type'];
                $this->data['PictureProduct']['size'] = $this->data['Picture']["product_{$i}"]['size'];

                //var_dump($this->data);
                $this->data['PictureProduct']['image'] = $fileData;
                if ($this->PictureProduct->save($this->data)) {
                    $this->Product->saveField("has_picture_{$i}", true);
                    return true;
                }
            }
        }
        // ไม่ได้ upload picture ขึ้นมา
        return true;
    }

    function delete_barcode($product_id) {
        $is_success = true;
        $this->Product->query('BEGIN');
        // clear flag ใน Product
        $this->Product->id = $product_id;
        $is_success &= $this->Product->saveField("has_barcode", false);

        // ลบรูปออกจากตาราง
        $is_success &= $this->PictureBarcode->delete($product_id);

        if ($is_success) {
            $this->Product->query("COMMIT");
            ;
            $this->Session->setFlash("Barcode delete succesfull.", 'flash/ok');
            $product_id = $this->Product->id;
        } else {
            $this->Product->query("ROLLBACK");
            $this->Session->setFlash("Barcode delete fail.", 'flash/fail');
        }
        $this->setAction('view', $product_id);
    }

    function delete_picture($product_id, $num) {
        $is_success = true;
        $this->Product->query('BEGIN');
        // clear flag ใน Product
        $this->Product->id = $product_id;
        $is_success &= $this->Product->saveField("has_picture_{$num}", false);

        // ลบรูปออกจากตาราง
        $is_success &= $this->PictureProduct->deleteAll(array('product_id' => $product_id, 'num' => $num));

        if ($is_success) {
            $this->Product->query("COMMIT");
            ;
            $this->Session->setFlash("Picture delete succesfull.", 'flash/ok');
            $product_id = $this->Product->id;
        } else {
            $this->Product->query("ROLLBACK");
            $this->Session->setFlash("Picture delete fail.", 'flash/fail');
        }
        $this->setAction('view', $product_id);
    }

    function barcode_image($product_id) {
        $image = $this->PictureBarcode->findByProductId($product_id);
        $this->image($image['PictureBarcode']['type'], $image['PictureBarcode']['size'], $image['PictureBarcode']['image']);
    }

    function product_image($product_id, $num) {
        $conditions = array("product_id = $product_id AND num = $num");
        $image = $this->PictureProduct->find('first', array('conditions' => $conditions));
        $this->image($image['PictureProduct']['type'], $image['PictureProduct']['size'], $image['PictureProduct']['image']);
    }

    function view($id = null) {
        if ($id != null) {
            $this->data = $this->Product->find('first', array('conditions' => array('Product.id' => $id)));

            $this->_neighbors($id, $this->Product, array('fields' => array('id', 'part_no')));
            
            $this->set('customers', $this->Customer->find('list'));
            $this->set('mode', 'edit');
            
            $special_part_no = $this->data['Supplier']['special_part_no'];
            if ($special_part_no == true) {
                $this->data['Product']['special_supplier'] = substr($this->data['Product']['part_no'], 0, 3);
                $this->data['Product']['special_part_no'] = substr($this->data['Product']['part_no'], 4);
            } else {
                $this->data['Product']['name'] = substr($this->data['Product']['part_no'], 10);
            }
            $this->set('special_part_no', $special_part_no);
            
        } else {
            $this->set('mode', 'add');
            $this->set('units', $this->Product->Unit->find('list'));
            $this->set('periods', $this->Period->find('list'));
        }
        // กรณี Special part no
        $this->set('special_categories', $this->Product->Category->find('list', array('fields' => array('id', 'name'), 'order' => 'name')));
        // กรณี part no ปกติ
        $this->set('categories', $this->Product->Category->find('list', array('fields' => array('id', 'code'))));
        $this->set('suppliers', $this->Product->Supplier->find('list', array('fields' => array('id', 'code'))));
        $this->set('itsTypes', $this->Product->ItsType->find('list', array('fields' => array('id', 'code'))));
    }

    function delete($id = null) {
        // ถ้ายังไม่เคย Stock in Product นี้แสดงว่าลบได้
        if ($id != null) {
            if (!$this->ItsStockIn->hasAny(array('product_id' => $id))) {
                if ($this->Product->delete($id)) {
                    $this->Session->setFlash("Product delete succesfull.", 'flash/ok');
                } else {
                    $this->Session->setFlash("Can not delete this product.", 'flash/fail');
                }
            } else {
                $this->Session->setFlash("Can not delete this product.", 'flash/fail');
            }
        }
        $this->setAction('display');
    }

    function inplace_editor($field, $id) {
        parent::inplace_editor($this->Product, $field, $id);
    }

    function popup_search() {
        parent::popup_search();

        $this->set('categories', $this->Product->Category->find('list', array('fields' => array('Category.id', 'Category.name'), 'order' => 'name')));
        $this->set('suppliers', $this->Product->Supplier->find('list', array('fields' => array('Supplier.id', 'Supplier.name'), 'order' => 'name')));
        $this->set('brands', $this->Product->Brand->find('list', array('fields', array('brand.id', 'brand.name'))));
        $this->set('types', $this->Product->ItsType->find('list', array('field', array('type.id', 'type.code'), 'order' => 'name')));
        $this->set('customers', $this->Customer->find('list', array('order' => 'name')));
        $this->set('operands', array('<' => '<', '<=' => '<=', '=' => '=', '>' => '>', '>=' => '>='));
        $this->set('popupWidth', 850);
    }

    /**
     * ถูกเรียกมาจาก ItsStocksInController::view()
     */
    function json_find_by_part_no_supplier() {
        $this->layout = 'ajax';
        $data = $this->Product->find('first', array(
                    'conditions' => array(
                        'part_no' => $this->data['part_no'],
                        'Product.supplier_id' => $this->data['supplier_id']
                    )
                        )
        );

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }

    /**
     * download template ไฟล์ csv สำหรับ import ITS Product
     */
    function template() {
        parent::template('vmi_products.csv');
    }

    /**
     * download template ไฟล์ csv สำหรับ import CustProductSite ตาม Customer, Site, Vendor และ Brand ที่ระบุเข้ามา
     */
    function template_cust() {
        $site_id = $this->data['Product']['site_id'];
        $this->CustProductSite->Site->id = $site_id;
        parent::template('vmi_customer_products_' . $this->CustProductSite->Site->field('name') . '.csv');

        $conditions = array();
        $this->set('customer_id', $this->data['Product']['customer_id']);
        $this->set('site_id', $site_id);
        $this->set('supplier_id', $this->data['Product']['supplier_id']);
        $this->set('dispatch_from', $this->data['Product']['dispatch_from']);

        if (!empty($this->data['Product']['supplier_id'])) {
            $conditions['Product.supplier_id'] = $this->data['Product']['supplier_id'];
        }
        if (!empty($this->data['Product']['brand_id'])) {
            $conditions['Product.brand_id'] = $this->data['Product']['brand_id'];
        }
        if (!empty($this->data['Product']['part_no_start'])) {
            $conditions['Product.part_no BETWEEN ? AND ?'] = array(strtoupper($this->data['Product']['part_no_start']), strtoupper($this->data['Product']['part_no_end']));
        }
        $limit = null;
        if (!empty($this->data['Product']['limit'])) {
            $limit = $this->data['Product']['limit'];
        }

        $this->Product->contain();
        $this->data = $this->Product->find('all', array(
                    'conditions' => $conditions,
                    'order' => 'id DESC',
                    'limit' => $limit
                ));
    }

    function import() {
        // มีการ upload ไฟล์เข้ามา
        if (!empty($this->data)) {
            if (is_uploaded_file($this->data['Product']['file']['tmp_name'])) {
                $is_success = true;

                // อ่านไฟล์ที่ upload เข้ามา
                $fileData = fread(fopen($this->data['Product']['file']['tmp_name'], "r"),
                                $this->data['Product']['file']['size']);

                // แบ่งข้อมูลที่เข้ามาแต่ละแถวด้วย REGEX
                $lines = preg_split('/\r\n/', $fileData);

                // เช็คแถวแรก header ที่เข้ามาว่าจำนวน field ตรงกับ template ล่าสุดหรือไม่?
                $HEADER = 'part_no,supplier_id,category_id,type_id,brand_id,model,title,description,supplier_part_no,unit_id,cost,price';
                if (strcmp($lines[0], $HEADER) != 0) {
                    $this->Session->setFlash("Invalid template file!!<br /> Please download a new template file.", 'flash/fail');
                } else {
                    $errMessage = 'Import Product fail. <br />';

                    $collector_id = $this->Auth->user('id');

                    // loop save ทีละ แถว
                    $count = count($lines);

                    // ignore line 1 column head
                    $data = array();
                    for ($i = 1; $i < $count; ++$i) {

                        // ถ้าไม่ใช่แถวว่างสุดท้าย
                        if (!empty($lines[$i])) {
//                            debug($lines[$i]);

                            $data [] = $this->_setProduct($lines[$i]);
                            $data[$i - 1]['Product']['collector_id'] = $collector_id;

                            // ตรวจสอบความถูกต้องของ product ก่อน แล้วจึง save
                            if (empty($data[$i - 1]['Product']['part_no']) || $this->Product->hasAny(array('part_no' => $data[$i - 1]['Product']['part_no']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Duplicated Product part no. "' . $data[$i - 1]['Product']['part_no'] . '"<br />';
                                $is_success = false;
                            } elseif (empty($data[$i - 1]['Product']['supplier_id']) || !$this->Product->Supplier->hasAny(array('id' => $data[$i - 1]['Product']['supplier_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Supplier ID (Vendor)"' . $data[$i - 1]['Product']['supplier_id'] . '"<br />';
                                $is_success = false;
                            } elseif (empty($data[$i - 1]['Product']['category_id']) || !$this->Product->Category->hasAny(array('id' => $data[$i - 1]['Product']['category_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Category ID "' . $data[$i - 1]['Product']['category_id'] . '"<br />';
                                $is_success = false;
                            } elseif (empty($data[$i - 1]['Product']['type_id']) || !$this->Product->ItsType->hasAny(array('id' => $data[$i - 1]['Product']['type_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Type ID "' . $data[$i - 1]['Product']['type_id'] . '"<br />';
                                $is_success = false;
                            } elseif (empty($data[$i - 1]['Product']['brand_id']) || !$this->Product->Brand->hasAny(array('id' => $data[$i - 1]['Product']['brand_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Brand ID "' . $data[$i - 1]['Product']['brand_id'] . '"<br />';
                                $is_success = false;
                            } elseif (empty($data[$i - 1]['Product']['unit_id']) || !$this->Product->Unit->hasAny(array('id' => $data[$i - 1]['Product']['unit_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Unit ID "' . $data[$i - 1]['Product']['unit_id'] . '"<br />';
                                $is_success = false;
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['Product']['cost'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Product Cost "' . $data[$i - 1]['Product']['cost'] . '" is not a number.<br />';
                                $is_success = false;
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['Product']['price'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Product Price "' . $data[$i - 1]['Product']['price'] . '" is not a number.<br />';
                                $is_success = false;
                            }
                        }
                    }

                    if ($is_success) {
                        $is_success &= $this->Product->saveAll($data, array('validate' => false));
                    }

                    if ($is_success == true) {
                        $this->Session->setFlash("Import Product succesfull.", 'flash/ok');
                        $product_id = $this->Product->id;
                    } else {
                        $this->Session->setFlash($errMessage, 'flash/fail');
                    }
                }
            }
            $this->redirect('display');
        } else {

            // เรียกหน้า popup ให้ browse file เข้ามา
            $this->layout = 'popup';
            $this->set('popupTitle', 'Import Product & Customer Information');
            $this->set('customers', $this->Customer->find('list'));
            $this->set('suppliers', $this->Product->Supplier->find('list'));
            $this->set('popupWidth', 700);
        }
    }

    /**
     * สำหรับ Import ITS Product
     * @param <type> $lines
     * @return <type>
     */
    function _setProduct($lines) {
        $a = str_getcsv($lines);
        $j = 0;
        $data = array();
        $data['Product']['id'] = null;
        $data['Product']['part_no'] = $a[$j++];
        $data['Product']['supplier_id'] = $a[$j++];
        $data['Product']['category_id'] = $a[$j++];
        $data['Product']['type_id'] = $a[$j++];
        $data['Product']['brand_id'] = $a[$j++];
        $data['Product']['model'] = $a[$j++];
        $data['Product']['title'] = $a[$j++];
        $data['Product']['text'] = $a[$j++];
        $data['Product']['supplier_part_no'] = $a[$j++];
        $data['Product']['unit_id'] = $a[$j++];
        $data['Product']['cost'] = $a[$j++];
        $data['Product']['price'] = $a[$j++];
        return $data;
    }

    function import_cust() {
        // มีการ upload ไฟล์เข้ามา
        if (!empty($this->data)) {
            if (is_uploaded_file($this->data['Product']['file']['tmp_name'])) {
                $is_success = true;

                // อ่านไฟล์ที่ upload เข้ามา
                $fileData = fread(fopen($this->data['Product']['file']['tmp_name'], "r"),
                                $this->data['Product']['file']['size']);

                // แบ่งข้อมูลที่เข้ามาแต่ละแถวด้วย REGEX
                $lines = preg_split('/\r\n/', $fileData);

                // เช็คแถวแรก header ที่เข้ามาว่าจำนวน field ตรงกับ template ล่าสุดหรือไม่?
                $HEADER = 'part_no,customer_id,site_id,supplier_id,dispatch_from,stock_code,description,price,mc,fluid,temp,pressure,ex_stock,min_stock,max_stock,critical_part,critical_mc,cycle_time,cycle_time_period_id,shortest_life_cycle,shortest_life_cycle_period_id,maintenance_plan,maintenance_plan_period_id,next_maintanence_date,last_maintanence_date,complete_consignment_date';
                if (strcmp($lines[0], $HEADER) != 0) {
                    $this->Session->setFlash("Invalid template file!!<br /> Please download a new template file.", 'flash/fail');
                } else {
                    $errMessage = 'Import Customer Product Information fail. <br />';

                    // loop save ทีละ แถว
                    $count = count($lines);

                    $collector_id = $this->Auth->user('id');

                    // ignore line 1 column head
                    $data = array();
                    for ($i = 1; $i < $count; ++$i) {

                        // ถ้าไม่ใช่แถวว่างสุดท้าย
                        if (!empty($lines[$i])) {
//                            debug($lines[$i]);

                            $data [] = $this->_setCustProduct($lines[$i]);
                            $data[$i - 1]['CustProductSite']['collector_id'] = $collector_id;

                            // ตรวจสอบความถูกต้องของ product ก่อน แล้วจึง save
                            // Product Id ถูกต้องมั้ย

                            $this->Product->contain();
                            $product = $this->Product->findByPartNo($data[$i - 1]['CustProductSite']['part_no']);
                            if ($product == null) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Part no. "' . $data[$i - 1]['CustProductSite']['part_no'] . '"<br />';
                                $is_success = false;
                                break;
                            }
                            $data[$i - 1]['CustProductSite']['product_id'] = $product['Product']['id'];
                            // Product part no นี้มี stock code แล้ว
                            if ($this->CustProductSite->hasAny(array('product_id' => $data[$i - 1]['CustProductSite']['product_id'], 'site_id' => $data[$i - 1]['CustProductSite']['site_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Part No. "' . $data[$i - 1]['CustProductSite']['part_no'] . '" already has stock code in this Customer Site.<br />';
                                $is_success = false;

                                // Supplier Id ถูกต้องมั้ย
                            } elseif (empty($data[$i - 1]['CustProductSite']['supplier_id']) || !$this->Product->Supplier->hasAny(array('id' => $data[$i - 1]['CustProductSite']['supplier_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Product Supplier ID (Vendor)"' . $data[$i - 1]['CustProductSite']['supplier_id'] . '"<br />';
                                $is_success = false;

                                // Customer Id ถูกต้องมั้ย
                            } elseif (empty($data[$i - 1]['CustProductSite']['customer_id']) || !$this->CustProductSite->Customer->hasAny(array('id' => $data[$i - 1]['CustProductSite']['customer_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Customer ID "' . $data[$i - 1]['CustProductSite']['customer_id'] . '"<br />';
                                $is_success = false;

                                // Site Id ถูกต้องมั้ย
                            } elseif (empty($data[$i - 1]['CustProductSite']['site_id']) || !$this->CustProductSite->Site->hasAny(array('id' => $data[$i - 1]['CustProductSite']['site_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Site ID "' . $data[$i - 1]['CustProductSite']['site_id'] . '"<br />';
                                $is_success = false;

                                // dispatch from ถูกต้องมั้ย เป็น 'its' หรือ 'supplier' หรือเปล่า
                            } elseif (empty($data[$i - 1]['CustProductSite']['dispatch_from']) ||
                                    (($data[$i - 1]['CustProductSite']['dispatch_from'] != 'its') && ($data[$i - 1]['CustProductSite']['dispatch_from'] != 'supplier'))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Dispatch from "' . $data[$i - 1]['CustProductSite']['brand_id'] . '" Please specify "its" OR "supplier"<br />';
                                $is_success = false;

                                // ไม่ใส่ stock code เข้ามา
                            } elseif (empty($data[$i - 1]['CustProductSite']['stock_code'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Please specify Stock Code<br />';
                                $is_success = false;

                                // Stock code ซ้ำ ใน site เดียวกัน
                            } elseif ($this->CustProductSite->hasAny(array('stock_code' => $data[$i - 1]['CustProductSite']['stock_code'], 'site_id' => $data[$i - 1]['CustProductSite']['site_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Duplicated Stock Code "' . $data[$i - 1]['CustProductSite']['stock_code'] . '"<br />';
                                $is_success = false;

                                // price เป็นตัวเลขหรือเปล่า
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['CustProductSite']['price'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Product Price "' . $data[$i - 1]['CustProductSite']['price'] . '" is not a number.<br />';
                                $is_success = false;

                                // min_stock เป็นตัวเลขหรือเปล่า
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['CustProductSite']['min_stock'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Product Min Stock"' . $data[$i - 1]['CustProductSite']['min_stock'] . '" is not a number.<br />';
                                $is_success = false;

                                // max_stock เป็นตัวเลขหรือเปล่า
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['CustProductSite']['max_stock'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Product Max Stock"' . $data[$i - 1]['CustProductSite']['max_stock'] . '" is not a number.<br />';
                                $is_success = false;

                                // หน่วยวันถูกมั้ย
                            } elseif (!empty($data[$i - 1]['CustProductSite']['cycle_time_period_id']) && !$this->Period->hasAny(array('id' => $data[$i - 1]['CustProductSite']['cycle_time_period_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Cycle Time Period ID"' . $data[$i - 1]['CustProductSite']['cycle_time_period_id'] . '"<br />';
                                $is_success = false;

                                // หน่วยวันถูกมั้ย
                            } elseif (!empty($data[$i - 1]['CustProductSite']['shortest_life_cycle_period_id']) && !$this->Period->hasAny(array('id' => $data[$i - 1]['CustProductSite']['shortest_life_cycle_period_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Shortest Life Cycle Period ID"' . $data[$i - 1]['CustProductSite']['shortest_life_cycle_period_id'] . '"<br />';
                                $is_success = false;

                                // หน่วยวันถูกมั้ย
                            } elseif (!empty($data[$i - 1]['CustProductSite']['maintenance_plan_period_id']) && !$this->Period->hasAny(array('id' => $data[$i - 1]['CustProductSite']['maintenance_plan_period_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Maintenance Plan Period ID"' . $data[$i - 1]['CustProductSite']['maintenance_plan_period_id'] . '"<br />';
                                $is_success = false;
                            }
                        }
                    }
                    if ($is_success) {
                        $is_success &= $this->CustProductSite->saveAll($data, array('validate' => false));
                    }

                    if ($is_success == true) {
                        $this->Session->setFlash("Import Product succesfull.", 'flash/ok');
                        $product_id = $this->Product->id;
                    } else {
                        $this->Session->setFlash($errMessage, 'flash/fail');
                    }
                }
            }
        }
        $this->redirect('display');
    }

    function _setCustProduct($lines) {
        $a = str_getcsv($lines);
        $j = 0;
        $data = array();
        $data['CustProductSite']['id'] = null;
        $data['CustProductSite']['part_no'] = $a[$j++];
        $data['CustProductSite']['customer_id'] = $a[$j++];
        $data['CustProductSite']['site_id'] = $a[$j++];
        $data['CustProductSite']['supplier_id'] = $a[$j++];
        $data['CustProductSite']['dispatch_from'] = $a[$j++];
        $data['CustProductSite']['stock_code'] = $a[$j++];
        $data['CustProductSite']['text'] = !empty($a[$j++]) ? $a[$j - 1] : null;
        $data['CustProductSite']['price'] = $a[$j++];
        $data['CustProductSite']['mc'] = !empty($a[$j++]) ? $a[$j - 1] : null;
        $data['CustProductSite']['fluid'] = !empty($a[$j++]) ? $a[$j - 1] : null;
        $data['CustProductSite']['temp'] = $a[$j++];
        $data['CustProductSite']['pressure'] = $a[$j++];
        $data['CustProductSite']['ex_stock'] = $a[$j++];
        $data['CustProductSite']['min_stock'] = $a[$j++];
        $data['CustProductSite']['max_stock'] = $a[$j++];
        $data['CustProductSite']['critical_part'] = $a[$j++];
        $data['CustProductSite']['critical_mc'] = $a[$j++];
        $data['CustProductSite']['cycle_time'] = $a[$j++];
        $data['CustProductSite']['cycle_time_period_id'] = $a[$j++];
        $data['CustProductSite']['shortest_life_cycle'] = $a[$j++];
        $data['CustProductSite']['shortest_life_cycle_period_id'] = $a[$j++];
        $data['CustProductSite']['maintenance_plan'] = $a[$j++];
        $data['CustProductSite']['maintenance_plan_period_id'] = $a[$j++];
        $data['CustProductSite']['next_maintanence_date'] = $a[$j++];
        $data['CustProductSite']['last_maintanence_date'] = $a[$j++];
        $data['CustProductSite']['complete_consignment_date'] = $a[$j++];
        return $data;
    }

    /**
     * template สำหรับ update ราคา CustProductSite
     */
    function template_cust_price() {
        $site_id = $this->data['Product']['site_id'];
        $this->CustProductSite->Site->id = $site_id;
        parent::template('vmi_customer_products_price_' . $this->CustProductSite->Site->field('name') . '.csv');

        $conditions = array();
        $this->set('customer_id', $this->data['Product']['customer_id']);
        $this->set('site_id', $site_id);
        $this->set('supplier_id', $this->data['Product']['supplier_id']);
        $this->set('dispatch_from', $this->data['Product']['dispatch_from']);

        if (!empty($this->data['Product']['supplier_id'])) {
            $conditions['CustProductSite.supplier_id'] = $this->data['Product']['supplier_id'];
        }
        if (!empty($this->data['Product']['brand_id'])) {
            $conditions['Product.brand_id'] = $this->data['Product']['brand_id'];
        }
        $conditions['CustProductSite.customer_id'] = $this->data['Product']['customer_id'];
        $conditions['CustProductSite.site_id'] = $this->data['Product']['site_id'];

        $this->CustProductSite->contain(array('Product'));
        $this->data = $this->CustProductSite->find('all', array(
                    'conditions' => $conditions,
                    'order' => 'CustProductSite.stock_code ASC',
                ));
    }

    /**
     * import การ update CustProductSite Price
     */
    function import_cust_price() {
        // มีการ upload ไฟล์เข้ามา
        if (!empty($this->data)) {
            if (is_uploaded_file($this->data['Product']['file']['tmp_name'])) {
                $is_success = true;

                // อ่านไฟล์ที่ upload เข้ามา
                $fileData = fread(fopen($this->data['Product']['file']['tmp_name'], "r"),
                                $this->data['Product']['file']['size']);

                // แบ่งข้อมูลที่เข้ามาแต่ละแถวด้วย REGEX
                $lines = preg_split('/\r\n/', $fileData);

                // เช็คแถวแรก header ที่เข้ามาว่าจำนวน field ตรงกับ template ล่าสุดหรือไม่?
                $HEADER = 'id,part_no,stock_code,customer_id,site_id,supplier_id,dispatch_from,description,price,stock_out_type,min_stock,max_stock';
                if (strcmp($lines[0], $HEADER) != 0) {
                    $this->Session->setFlash("Invalid template file!!<br /> Please download a new template file.", 'flash/fail');
                } else {
                    $errMessage = 'Update Customer Product Price fail. <br />';

                    // loop save ทีละ แถว
                    $count = count($lines);

                    $collector_id = $this->Auth->user('id');

                    // ignore line 1 column head
                    $data = array();
                    for ($i = 1; $i < $count; ++$i) {

                        // ถ้าไม่ใช่แถวว่างสุดท้าย
                        if (!empty($lines[$i])) {
//                            debug($lines[$i]);

                            $data [] = $this->_setCustProductPrice($lines[$i]);
                            $data[$i - 1]['CustProductSite']['collector_id'] = $collector_id;

                            // ตรวจสอบความถูกต้องของ product ก่อน แล้วจึง save
                            // Product Id ถูกต้องมั้ย

                            $this->CustProductSite->contain();
                            $cps = $this->CustProductSite->findById($data[$i - 1]['CustProductSite']['id']);
                            if ($cps == null) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Id. "' . $data[$i - 1]['CustProductSite']['id'] . '"<br />';
                                $is_success = false;
                                break;
                            }
                            if ($data[$i - 1]['CustProductSite']['stock_code'] != $cps['CustProductSite']['stock_code']) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Stock code. "' . $data[$i - 1]['CustProductSite']['stock_code'] . '" for Id "' . $cps['CustProductSite']['id'] . '"<br />';
                                $is_success = false;
                                break;
                            }
                            // Supplier Id ถูกต้องมั้ย
                            if (empty($data[$i - 1]['CustProductSite']['supplier_id']) || !$this->Product->Supplier->hasAny(array('id' => $data[$i - 1]['CustProductSite']['supplier_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Invalid Product Supplier ID (Vendor)"' . $data[$i - 1]['CustProductSite']['supplier_id'] . '"<br />';
                                $is_success = false;

                                // Customer Id ถูกต้องมั้ย
                            } elseif (empty($data[$i - 1]['CustProductSite']['customer_id']) || !$this->CustProductSite->Customer->hasAny(array('id' => $data[$i - 1]['CustProductSite']['customer_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Invalid Customer ID "' . $data[$i - 1]['CustProductSite']['customer_id'] . '"<br />';
                                $is_success = false;

                                // Site Id ถูกต้องมั้ย
                            } elseif (empty($data[$i - 1]['CustProductSite']['site_id']) || !$this->CustProductSite->Site->hasAny(array('id' => $data[$i - 1]['CustProductSite']['site_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Invalid Site ID "' . $data[$i - 1]['CustProductSite']['site_id'] . '"<br />';
                                $is_success = false;

                                // dispatch from ถูกต้องมั้ย เป็น 'its' หรือ 'supplier' หรือเปล่า
                            } elseif (empty($data[$i - 1]['CustProductSite']['dispatch_from']) ||
                                    (($data[$i - 1]['CustProductSite']['dispatch_from'] != 'its') && ($data[$i - 1]['CustProductSite']['dispatch_from'] != 'supplier'))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Invalid Dispatch from "' . $data[$i - 1]['CustProductSite']['brand_id'] . '" Please specify "its" OR "supplier"<br />';
                                $is_success = false;
                                // price เป็นตัวเลขหรือเปล่า
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['CustProductSite']['price'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Price "' . $data[$i - 1]['CustProductSite']['price'] . '" is not a number.<br />';
                                $is_success = false;
                                // min_stock เป็นตัวเลขหรือเปล่า
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['CustProductSite']['min_stock'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Min Stock "' . $data[$i - 1]['CustProductSite']['min_stock'] . '" is not a number.<br />';
                                $is_success = false;
                                // max_stock เป็นตัวเลขหรือเปล่า
                            } elseif (preg_match('/[a-zA-Z]+/', $data[$i - 1]['CustProductSite']['max_stock'])) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Max Stock "' . $data[$i - 1]['CustProductSite']['max_stock'] . '" is not a number.<br />';
                                $is_success = false;
                                // min_stock < max_stcok ?
                            } elseif ($data[$i - 1]['CustProductSite']['min_stock'] > $data[$i - 1]['CustProductSite']['max_stock']) {
                                $errMessage .= 'Line #' . ($i + 1) . ' ' . $data[$i - 1]['CustProductSite']['stock_code'] . ' Min Stock is greater than Max Stock "(' . $data[$i - 1]['CustProductSite']['min_stock'] . ' > ' . $data[$i - 1]['CustProductSite']['max_stock'] . '").<br />';
                                $is_success = false;
                            }
                        }
                    }
                    if ($is_success) {
                        $is_success &= $this->CustProductSite->saveAll($data, array('validate' => false));
                    }

                    if ($is_success == true) {
                        $this->Session->setFlash("Update Customer Product Prices succesfull.", 'flash/ok');
                        $product_id = $this->Product->id;
                    } else {
                        $this->Session->setFlash($errMessage, 'flash/fail');
                    }
                }
            }
        }
        $this->redirect('display');
    }

    function _setCustProductPrice($lines) {
        $a = str_getcsv($lines);
        $j = 0;
        $data = array();
        // HEADER => id,part_no,stock_code,customer_id,site_id,supplier_id,dispatch_from,description,price
        $data['CustProductSite']['id'] = $a[$j++];
        $data['CustProductSite']['part_no'] = $a[$j++];
        $data['CustProductSite']['stock_code'] = $a[$j++];
        $data['CustProductSite']['customer_id'] = $a[$j++];
        $data['CustProductSite']['site_id'] = $a[$j++];
        $data['CustProductSite']['supplier_id'] = $a[$j++];
        $data['CustProductSite']['dispatch_from'] = $a[$j++];
        $data['CustProductSite']['text'] = !empty($a[$j++]) ? $a[$j - 1] : null;
        $data['CustProductSite']['price'] = $a[$j++];
        $data['CustProductSite']['stock_out_type'] = $a[$j++];
        $data['CustProductSite']['min_stock'] = $a[$j++];
        $data['CustProductSite']['max_stock'] = $a[$j++];
        return $data;
    }

    function print_display() {
        $this->layout = 'print';
        $this->_setReportNote();
        $this->paginate['Product']['limit'] = 9999;
        $this->display();
        $this->render('print_display');
    }

    function excel_display() {
        parent::excel('VMI PRODUCT INVENTORY');
        $this->_setReportNote();
        $this->paginate['Product']['limit'] = 9999;
        $this->display();
        $this->render('excel_display');
    }

    function _setReportNote() {
        $this->set('report_by', $this->Auth->user('name'));
        $this->set('print_orientation', PRINT_LANDSCAPE);
    }

    /**
     * popup นี้จะเหมือนหน้า display เอามาแสดงเป็น popup สามารถเลือก product แล้วส่ง part no กลับไปหน้าที่เรียกมาได้
     */
    function popup_view() {
        $this->layout = 'popup';
        // clear session การ search จากครั้งก่อน
        $this->Session->delete('Product');
        $this->Session->delete('Products');
        $this->Session->delete("CustProductSite.paging.site_id");
        $this->Session->delete("CustProductSite.paging.customer_id");

        // ถ้ามีการส่ง supplier_id เข้ามา เพิ่มในเงื่อนไขการ search เลย
        if (isset($this->passedArgs['supplier_id'])) {
            $supplier_id = $this->passedArgs['supplier_id'];
        } else {
            $supplier_id = null;
        }

        // ถ้ามีการส่ง site_id เข้ามา เพิ่มในเงื่อนไขการ search เลย
        if (isset($this->passedArgs['site_id'])) {
            $site_id = $this->passedArgs['site_id'];
            $this->Site->id = $site_id;
            $customer_id = $this->Site->field('customer_id');
            $this->set('sites', $this->Site->find('list', array('order' => 'customer_id, name', 'conditions' => array('customer_id' => $customer_id))));
        } else {
            $customer_id = null;
            $site_id = null;
            $this->set('sites', null);
        }

        $this->set('popupTitle', 'Select a Product');
        $this->set('popupWidth', '$j(document).width() - 100');

        // supplier id ที่จะถูกเลือกเป็น default
        $this->set('supplier_id', $supplier_id);
        $this->set('site_id', $site_id);
        $this->set('customer_id', $customer_id);

        $this->set('suppliers', $this->Product->Supplier->find('list'));
        $this->set('brands', $this->Product->Brand->find('list'));
        $this->set('categories', $this->Product->Category->find('list'));
        $this->set('types', $this->Product->ItsType->find('list'));
        $this->set('customers', $this->Customer->find('list', array('order' => 'name')));
    }

    /**
     * ใช้ร่วมกับ popup_view เป็นส่วนตารางแสดงแถว customers
     */
    function popup_paginate() {
        if (isset($this->passedArgs['supplier_id'])) {
            $this->data['Product']['supplier_id'] = $this->passedArgs['supplier_id'];
        }
        if (isset($this->passedArgs['site_id'])) {
            $this->data['CustProductSite']['site_id'] = $this->passedArgs['site_id'];
        }
        if (isset($this->passedArgs['customer_id'])) {
            $this->data['CustProductSite']['customer_id'] = $this->passedArgs['customer_id'];
        }


        $this->display();
    }

    /**
     * ปรับราคา Product cost/price
     * @param <type> $id
     * @param <type> $type
     */
    function change_price($id, $type) {
        // cost || price
        $field = $type;

        parent::inplace_editor($this->Product, $field, $id);

        $price = trim($this->params['form']['value']);
        echo $price;
        exit;
    }

    function popup_view_price($id, $type) {
        $this->layout = 'popup';

        $this->Product->id = $id;
        $this->set('popupTitle', Inflector::humanize($type) . ' History : ' . $this->Product->field('part_no'));
        $this->set('popupWidth', 400);
        $this->set('type', Inflector::humanize($type));

        $this->data = $this->ProductPriceHistory->find('all', array(
            'conditions' => array(
                'product_id' => $id,
                'type' => $type
            ),
            'order' => 'created DESC',
            'contain' => array('User')
        ));
    }

}

?>